<template>
  <div class="mine">
    <div class="head">
      <div class="returnBtn" @click="$tab.navigateBack()">
        <image src="@/static/images/index/btn_closed@2x.png"></image>
      </div>
      <div class="article_title">我的</div>
    </div>

    <div v-if="!loginShow" class="contentInfo">
      <!-- 头像 -->
      <div class="leftinfo">
        <image @click="handleToAvatar" :src="avatar"></image>
      </div>

      <div class="rightinfo">
        <div class="userInfo">
          <div class="unser_l">
            <!-- 用户名 -->
            <div class="u_title">{{ name }}</div>

            <!-- 岗位信息 -->
            <div class="userButy">
              <div class="gangwei">岗位：{{ $store.state.user.postName }}</div>
              <div class="gongqu">公区：{{ $store.state.user.spaceName }}</div>
              <div class="gongsi">所属公司：{{ $store.state.user.company }}</div>
            </div>
          </div>

          <div class="unser_r">
            <div class="logOut" @click="handleLogout"></div>
          </div>
        </div>
        <div class="mineTest">
          <div class="exam_title" style="font-size: calc(100vw * 40 / 2560);">
            我的考试（{{ completedCount }}/{{ parperList.length }}）
          </div>
          <table class="article-table">
            <thead>
              <tr>
                <!-- <th style="width: calc(100vw * 300 / 2560);">序号</th> -->
                <th>考试题目</th>
                <th>考试时间</th>
                <th style="text-align: center;">当前状态</th>
                <th style="text-align: center;">是否通过</th>
                <th style="text-align: center;">分数</th>
                <th style="text-align: center;">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in parperList" :key="index">
                <!-- <td style="width: calc(100vw * 300 / 2560);">{{ String(index +
                  1).padStart(2, '0') }}</td> -->
                <td>{{ item.bitchName }}</td>
                <td>{{ item.startTime }} - {{ item.endTime }}</td>
                <!-- <td>{{ item.status }}</td> -->
                <td style="text-align: center;" v-if="item.status == null">-</td>
                <td style="text-align: center;" v-if="item.status == 0">未开始</td>
                <td style="text-align: center;" v-if="item.status == 1">进行中</td>
                <td style="text-align: center;" v-if="item.status == 2">已完成</td>
                <td style="text-align: center;" v-if="item.status == 3">已结束</td>
                <td style="text-align: center;" v-if="item.status == 4">未完成</td>
                <td style="text-align: center;">
                  <span v-if="item.isPass == 0" style="color: #F76666;">未通过</span>
                  <span v-if="item.isPass == 1">已通过</span>
                  <span v-if="item.isPass == 2">-</span>
                  <span v-if="item.isPass == 3">待审卷</span>
                </td>
                <td style="text-align: center;">
                  <span v-if="item.isPass == 1 || item.isPass == 0">{{ item.score }}</span>
                  <span v-if="item.isPass == 3">-</span>
                </td>
                <td
                  style="width: calc(100vw * 230 / 2560);text-align: center;font-size: calc(100vw * 32 / 2560);line-height:calc(100vw * 80 / 2560) ;">
                  <!-- <div class="detailBtn" @click="startExam(item)">开始答题</div> -->
                  <!-- <button @click="startExam(item)" v-if="item.status == 0 || item.status == 2"
                    :disabled="isExamTimeOut(item) || item.status == 2"
                    :class="['detailBtn1', { 'disabled': isExamTimeOut(item) || item.status == 2 }]">开始答题</button> -->
                  <button @click="startExam(item)" v-if="item.status == 0 || item.status == 2"
                    class="detailBtn1">开始答题</button>
                  <button @click="startExam(item)" v-if="item.status == 1" class="detailBtn2">开始答题</button>
                  <button @click="viewPaper(item)" v-if="item.status == 2" class="detailBtn1">查看试卷</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

    </div>

    <!-- 开始答题弹窗 -->
    <div class="mask" v-if="dialogVisible">

      <div class="goAnswer">
        <div class="top">开始考试</div>

        <div class="center">
          本次考试总计{{ answerdetail.exaParper.questionNum || 0 }}道题目，
          满分{{ answerdetail.exaParper.parperScore || 0 }}分，
          考试时间为{{ Math.floor((answerdetail.exaParper.answeringTime || 0) / 60) }}分钟，
          须在有效时间内提交考卷，超出时间后不可提交，是否确认开始考试？
        </div>

        <div class="bottom">
          <u-button type="primary" @click="cancel">返回</u-button>
          <u-button type="error" @click="goAnswer">确认开始</u-button>
        </div>
      </div>
    </div>


    <!-- 登录弹窗 -->
    <Login v-if="loginShow" @loginSuccess="loginSuccess" style="margin: calc(100vw * 120 / 2560) auto;color: #fff;" />
  </div>
</template>

<script>
import BasicLayout from '@/components/layout/basic-layout.vue'
import { getToken } from '@/utils/auth'
import Login from '@/components/login/index.vue'
import { getAssessList } from "@/api/login"
import { getUserPaperList, updateAnswerStatus } from "@/api/mine/index.js"
import { getArticleListByColumnId, getArticleDetailById, getParperInfo } from "@/api/index"

export default {
  components: {
    BasicLayout,
    Login
  },
  data() {
    return {
      name: this.$store.state.user.name,
      loginShow: false, // 控制登录弹窗显示
      parperList: [],// 用户试卷列表 
      userInfo: {}, // 用户信息
      dialogVisible: false, // 控制弹窗显示
      currentItem: null, // 当前选中的考试项
      answerdetail: {
        exaParper: {
          questionNum: 0, // 题目数量
          parperScore: 0, // 满分
          answeringTime: 0 // 考试时间（秒）
        }, // 试卷信息
        exaClassQuestionsList: [] // 试题列表
      }, // 答题详情
    }
  },

  computed: {

    avatar() {
      return this.$store.state.user.avatar
    },

    windowHeight() {
      return uni.getSystemInfoSync().windowHeight - 50
    },

    // 计算跳转链接
    examUrl() {
      if (!this.currentItem) return '';
      return `/pages/answerPage/index?parperId=${this.currentItem.parperId}&bitchId=${this.currentItem.bitchId}&bitchName=${this.currentItem.bitchName}&id=${this.currentItem.id}&type=${this.currentItem.status == 2 ? 1 : 0}&userId=${this.currentItem.userId}`;
    },

    // 计算已完成的试卷数量
    completedCount() {
      return this.parperList.filter(item => item.status == 2).length;
    },
  },

  onShow() {
    const token = getToken();
    if (token) {
      this.loginShow = false;
      this.getUserPaperList();
    }

    // 监听刷新事件
    uni.$on('refreshPaperList', this.getUserPaperList);
  },

  onHide() {
    // 移除监听
    uni.$off('refreshPaperList', this.getUserPaperList);
  },

  // 页面卸载时也要移除监听
  onUnload() {
    uni.$off('refreshPaperList', this.getUserPaperList);
  },
  mounted() {
    this.userInfo = JSON.parse(JSON.stringify(this.$store.state.user))
    console.log(this.userInfo);

    const token = getToken()

    if (!token) {
      this.loginShow = true
    } else {
      this.loginShow = false
      this.getUserPaperList(); // 获取用户试卷列表
    }

  },
  methods: {
    // 获取用户试卷列表
    getUserPaperList() {
      getUserPaperList().then(res => {
        console.log("getUserPaperList", res);
        this.parperList = res.rows || []
      })
    },

    // 获取试卷列表
    getDetail() {
      return getParperInfo({
        parperId: this.currentItem.parperId,
        bitchId: this.currentItem.bitchId,
        userId: this.currentItem.userId,
      }).then(res => {
        console.log('getDetail', res);
        if (res.code === 200 && res.data) {
          this.answerdetail = JSON.parse(JSON.stringify(res.data));
        }
      }).catch(err => {
        console.error('获取试卷详情失败:', err);
        this.$modal.showToast('获取试卷详情失败');
      });
    },

    // 跳转到答题页面
    goAnswer() {
      this.dialogVisible = false; // 关闭弹窗
      uni.navigateTo({
        url: this.examUrl,
        success: () => {
          console.log('跳转成功，传递的参数:', this.currentItem);
          this.updateAnswerStatus();

        },
        fail: (err) => {
          console.error('跳转失败:', err);
        }
      });
    },

    // 开始答题按钮修改状态
    updateAnswerStatus() {
      if (this.currentItem) {
        updateAnswerStatus({
          id: this.currentItem.id,
        }).then(res => {
          console.log('更新考试状态成功:', res);
        }).catch(err => {
          console.error('更新考试状态失败:', err);
          this.$modal.showToast('更新考试状态失败');
        });
      }
    },

    // 开始考试按钮
    startExam(item) {
      console.log('开始考试按钮', item);

      console.log('开始考试按钮', item);
      this.currentItem = item;
      // 先获取详情，成功后再显示弹窗
      this.getDetail().then(() => {
        this.dialogVisible = true;
      });
      // uni.navigateTo({
      //   url: this.url,
      //   success: () => {
      //     console.log('跳转成功，传递的参数:', item);
      //   },
      //   fail: (err) => {
      //     console.error('跳转失败:', err);
      //   }
      // });
    },

    // 查看试卷
    viewPaper(item) {
      console.log('查看试卷', item);
      uni.navigateTo({
        url: '/pages/answerPage/parperPre?parperId=' + item.parperId + '&bitchId=' + item.bitchId + '&bitchName=' + item.bitchName + '&id=' + item.id + '&type=' + item.status + '&userId=' + item.userId,
        success: () => {
          console.log('跳转成功，传递的参数:', item);
        },
        fail: (err) => {
          console.error('跳转失败:', err);
        }
      });
    },


    // 检查考试时间是否超出范围
    isExamTimeOut(item) {
      console.log('检查考试时间是否超出范围', item);

      const now = new Date().getTime();
      const startTime = new Date(item.startTime).getTime();
      const endTime = new Date(item.endTime).getTime();

      return now < startTime || now > endTime;
    },

    cancel() {
      this.currentItem = null; // 清除当前选中的考试项
      this.dialogVisible = false; // 关闭弹窗
    },

    handleToAvatar() {
      // this.$tab.navigateTo('/pages/mine/avatar/index')
    },

    // 注销登录
    handleLogout() {
      this.$modal.confirm('确定注销并退出系统吗？').then(() => {
        this.$store.dispatch('LogOut').then(() => { }).finally(() => {
          this.$tab.reLaunch('/pages/index')
        })
      })
    },

    loginSuccess(v) {
      console.log(v);
      if (v) {
        this.loginShow = false; // 隐藏登录弹窗
        this.getUserPaperList(); // 获取用户试卷列表
      } else {
        this.loginShow = true; // 显示登录弹窗
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.mine {
  width: 100vw;
  height: 100vh;
  background-color: #00063A;

  .head {
    width: 100vw;
    height: calc(100vw * 140 / 2560); // 高度按比例自适应
    background: url('@/static/images/index/bg_top2.png') no-repeat center center;
    background-size: cover;

    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 0 calc(100vw * 20 / 2560);

    .returnBtn {
      width: calc(100vw * 64 / 2560);
      height: calc(100vw * 64 / 2560);
      margin-right: calc(100vw * 30 / 2560);

      image {
        width: 100%;
        height: 100%;
      }
    }

    .article_title {
      font-size: calc(100vw * 40 / 2560);
      color: #FFFFFF;
      text-align: left;
    }
  }

  .contentInfo {
    width: calc(100vw * 2500 / 2560);
    height: calc(100vw * 1220 / 2560);
    // background: linear-gradient(135deg, rgba(65, 102, 255, 0.6) 0%, rgba(65, 102, 255, 0.05) 30%, rgba(255, 255, 255, 0) 100%);
    border-radius: calc(100vw * 24 / 2560);
    background: url('../../static/images/index/mine_bg@2x.png') no-repeat center center;
    background-size: cover;
    margin: calc(100vw * 40 / 2560) auto;
    padding: calc(100vw * 60 / 2560);
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;

    .leftinfo {
      width: calc(100vw * 300 / 2560);
      height: calc(100vw * 420 / 2560);
      background-color: #A7B8FF;
      border-radius: calc(100vw * 4 / 2560);

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .rightinfo {
      width: calc(100vw * 2100 / 2560);
      height: 100%;
      margin-left: calc(100vw * 80 / 2560);
      // border: 1px solid #E6E6E6;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;

      .userInfo {
        width: 100%;
        height: calc(100vw * 120 / 2560);
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #354480;

        .unser_l {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: flex-start;

          .u_title {
            font-size: calc(100vw * 40 / 2560);
            color: #EBEDF4;
            text-align: left;
          }

          .userButy {
            font-size: calc(100vw * 32 / 2560);
            color: #9CA0CE;
            text-align: left;
            display: flex;
            justify-content: start;
            align-items: center;

            .gangwei,
            .gongqu,
            .gongsi {
              min-width: calc(100vw * 400 / 2560);
              margin: calc(100vw * 20 / 2560) calc(100vw * 20 / 2560) calc(100vw * 38 / 2560) 0;
            }
          }
        }

        .unser_r {
          .logOut {
            width: calc(100vw * 160 / 2560);
            height: calc(100vw * 64 / 2560);
            background: url('../../static/images/index/btn_quit@2x.png') no-repeat center center;
            background-size: cover;
            cursor: pointer;
          }
        }
      }

      .mineTest {
        width: 100%;
        height: calc(100vw * 1000 / 2560);
        // background-color: #00063A;
        border-radius: calc(100vw * 24 / 2560);
        // padding: calc(100vw * 40 / 2560);
        // box-sizing: border-box;
        overflow-y: auto;

        .exam_title {
          font-size: calc(100vw * 32 / 2560) !important;
          margin-top: calc(100vw * 80 / 2560);
          color: #FFFFFF;
          text-align: left;
        }

        .article-table {
          width: 100%;
          border-collapse: collapse;
          color: #fff;

          th {
            font-size: calc(100vw * 32 / 2560);
            color: #8E95B8;
            text-align: left;
          }

          td {
            min-width: calc(100vw * 200 / 2560);
            font-size: calc(100vw * 32 / 2560);

            .detailBtn1,
            .detailBtn2 {
              width: calc(100vw * 230 / 2560);
              height: calc(100vw * 80 / 2560);
              font-size: calc(100vw * 32 / 2560);
              box-shadow: inset 0px 0px 4px 1px #1C0007;
              border-radius: calc(100vw * 99 / 2560);
              color: #FFFFFF;
            }

            .detailBtn1 {
              background: linear-gradient(#3670FF 0%, #1022D5 100%);

              &.disabled {
                background: linear-gradient(#999 0%, #666 100%);
                cursor: not-allowed;
                opacity: 0.6;
              }
            }

            .detailBtn2 {
              background: linear-gradient(180deg, #FF7171 0%, #BE1212 100%);
            }
          }

          th,
          td {
            border: none;
            border-bottom: 1px solid #354480;
            padding: calc(100vw *52 / 2560) calc(100vw * 8 / 2560);
            box-sizing: border-box;
            text-align: left;
            // text-align: center;
          }

          // tr:last-child td {
          //   border-bottom: none;
          // }

          tr:nth-child(even) {
            background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(51, 105, 251, 0.2) 49%, rgba(255, 255, 255, 0) 100%);
          }
        }
      }
    }
  }

  .mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba($color: #000114, $alpha: 0.6);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;

    .goAnswer {
      width: calc(100vw * 1024 / 2560);
      height: calc(100vw * 540 / 2560);
      background: url('@/static/images/index/bg_answer.png') no-repeat center center;
      background-size: cover;
      background-color: transparent;
      padding: 0 calc(100vw * 80 / 2560);
      box-sizing: border-box;
      z-index: 1000;
      color: #fff;
      position: fixed;
      bottom: 30%;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;

      .top {
        font-size: calc(100vw * 48 / 2560);
        color: #FFFFFF;
        text-align: center;
        padding-top: calc(100vw * 15 / 2560);
        box-sizing: border-box;
      }

      .center {
        width: calc(100vw * 863 / 2560);
        height: calc(100vw * 183 / 2560);
        ;
        font-size: calc(100vw * 40 / 2560);
        color: #FFFFFF;
        line-height: calc(100vw * 64 / 2560);
        text-align: left;
      }

      .bottom {
        width: 100%;
        height: calc(100vw * 120 / 2560);
        display: flex;
        justify-content: space-around;
        align-items: center;

        uni-button {
          width: calc(100vw * 230 / 2560);
          height: calc(100vw * 80 / 2560);
          border-radius: calc(100vw * 40 / 2560);
          font-size: calc(100vw * 32 / 2560) !important;
          border: none;
        }

        // bottom 里第一个按钮的样式
        :first-child {
          background: linear-gradient(180deg, #3670FF 0%, #1022D5 100%);
          box-shadow: inset 0px 0px 9px 1px #1C0007;
        }

        :last-child {
          background: linear-gradient(180deg, #FF7171 0%, #BE1212 100%);
          box-shadow: inset 0px 0px 9px 1px #1C0007;
          text-align: center;
        }
      }
    }
  }
}
</style>
